package service

import (
	"github.com/gin-gonic/gin"
	"github.com/mssola/user_agent"
	"perfect-admin/dao"
	"perfect-admin/global"
	"perfect-admin/model"
	"perfect-admin/model/request"
	"perfect-admin/utils"
	"time"
)

func GetLoginLogList(queryInfo request.QueryInfo) (err error, total int, logList []model.SysLoginLog) {
	table := dao.DB.Model(&model.SysLoginLog{}).Select("*")
	if queryInfo.IpAddr != "" {
		table = table.Where(&model.SysLoginLog{Ipaddr:queryInfo.IpAddr})
	}
	if queryInfo.Username != ""{
		table = table.Where(&model.SysLoginLog{Username:queryInfo.Username})
	}
	if queryInfo.Status != ""{
		table = table.Where(&model.SysLoginLog{Status:queryInfo.Status})
	}
	if queryInfo.PageSize != 0 && queryInfo.PageNum != 0 {
		if err = table.Order("info_id desc").Limit(queryInfo.PageSize).Offset((queryInfo.PageNum - 1) * queryInfo.PageSize).Find(&logList).Error; err != nil {
			return err, 0, nil
		}
	}else {
		if err = table.Order("info_id desc").Find(&logList).Error; err != nil {
			return err, 0, nil
		}
	}
	table.Count(&total)
	return
}

func AddOneLoginLog(log model.SysLoginLog) {
	log.CreateBy = "0"
	log.UpdateBy = "0"
	if err := dao.DB.Create(&log).Error; err != nil{
		global.LOG.Error(err)
	}
}

func InsertLoginLog(c *gin.Context, msg string, status string, username string) {
	var loginlog model.SysLoginLog
	ua := user_agent.New(c.Request.UserAgent())
	loginlog.Ipaddr = c.ClientIP()
	location := utils.GetLocation(c.ClientIP())
	loginlog.LoginLocation = location
	loginlog.LoginTime = time.Now()
	loginlog.Status = status
	loginlog.Remark = c.Request.UserAgent()
	browserName, browserVersion := ua.Browser()
	loginlog.Browser = browserName + " " + browserVersion
	loginlog.Os = ua.OS()
	loginlog.Platform = ua.Platform()
	loginlog.Msg = msg
	loginlog.Username = username
	if err := dao.DB.Create(&loginlog).Error; err != nil{
		global.LOG.Error(err)
	}
}

func BatchDeleteLoginLog(id []int) (err error) {
	err = dao.DB.Model(&model.SysLoginLog{}).Where("info_id in (?)", id).Delete(&model.SysLoginLog{}).Error
	return
}

func GetLoginLogByIds(ids []int) (logList []model.SysLoginLog, err error) {
	err = dao.DB.Model(&model.SysLoginLog{}).Where("info_id in (?)", ids).Find(&logList).Error
	return
}

func CleanLoginLog() error {
	return dao.DB.Unscoped().Delete(&model.SysLoginLog{}).Error
}
